package com.crm.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.crm.dao.GoodsDao;
import com.crm.entity.Goods;
import com.crm.service.GoodsService;

@Service
public class GoodsServiceImpl implements GoodsService{

	@Autowired
	private GoodsDao goodsDao;

	@Override
	public Page<Goods> findGoods(Integer pageIndex) {
		Goods goods = new Goods();
		goods.setPullOn(true);
		//创建实例
        Example<Goods> example = Example.of(goods);
        PageRequest pageable = new PageRequest(pageIndex,10,Sort.Direction.DESC,"addTime");
		
		return goodsDao.findAll(example, pageable);
	}

	@Override
	public Goods findGoodsById(String id) {
		if(StringUtils.isNotBlank(id)) {
			return goodsDao.findOne(id);
		}
		return null;
	}

	@Override
	public void addGoods(Goods goods) {
		if(goods.getAddTime() == null) {
			goods.setAddTime(new Date());
		}
		goodsDao.save(goods);
	}

	@Override
	public List<Goods> findGoodsByIds(List<String> goodsIds) {
		List<Goods> findAll = goodsDao.findAll(goodsIds);
		return findAll;
	}

	@Override
	public List<Goods> findGoodsByIds(String goodsIds) {
		if(StringUtils.isBlank(goodsIds)) {
			return null;
		}
		List<String> idList = Arrays.asList(goodsIds.split(","));
		if(null == idList || idList.size() ==0) {
			return null;
		}
		return findGoodsByIds(idList);
	}

	@Override
	public Page<Goods> findGoodsByPage(Integer pageIndex, String title) {
		Goods goods = new Goods();
		goods.setPullOn(true);
		if(StringUtils.isNotBlank(title)) {
			goods.setTitle(title);
		}
		//创建实例
        Example<Goods> example = Example.of(goods);
        PageRequest pageable = new PageRequest(pageIndex,10,Sort.Direction.DESC,"addTime");
		
		return goodsDao.findAll(example, pageable);
	}
}
